﻿using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.IdentityModel.Tokens;
using MyWeb.Common.DB;
using MyWeb.Common.Helper;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;

namespace MyWeb.Extensions.ServiceExtensions.Authorization
{
    /// <summary>
    /// 系统 授权服务 配置
    /// </summary>
    public static class AuthorizationSetup
    {
        public static void AddAuthorizationSetup(this IServiceCollection services)
        {
            if (services == null) throw new ArgumentNullException(nameof(services));

            services.AddSingleton<JwtSecurityTokenHandler>();

            #region 参数
            //读取配置文件
            var audience = AppSettings.app<Audience>("Audience").FirstOrDefault();


            var signingKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(audience.Secret));
            var Issuer = AppSettings.app(new string[] { "Audience", "Issuer" });
            //var Audience = AppSettings.app(new string[] { "Audience", "Audience" });
            

            var signingCredentials = new SigningCredentials(signingKey, SecurityAlgorithms.HmacSha256);

            // 如果要数据库动态绑定，这里先留个空，后边处理器里动态赋值
            var permission = new List<PermissionItem>();

            // 角色与接口的权限要求参数
            var permissionRequirement = new PermissionRequirement(
                "/api/denied",// 拒绝授权的跳转地址（目前无用）
                permission,
                ClaimTypes.Role,//基于角色的授权
                audience.Issuer,//发行人
                audience.Audien,//听众
                signingCredentials,//签名凭据
                expiration: 60//接口的过期时间(60分钟)
                );
            #endregion

            // 这里冗余写了一次,因为很多人看不到
            services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
            // 注入权限处理器
            //services.AddScoped<IAuthorizationHandler, PermissionHandler>();
            services.AddSingleton(permissionRequirement);


            if (AppSettings.app(new string[] { "Startup", "IdentityServer4", "Enabled" }).ObjToBool())
            {
                services.AddAuthentication("Bearer")
                .AddJwtBearer("Bearer", o =>
                {
                    o.Authority = $"{AppSettings.app(new string[] { "Startup", "IdentityServer4", "AuthorizationUrl" })}";
                    //o.Authority = "http://localhost:5000";
                    o.RequireHttpsMetadata = false;
                    o.TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters()
                    {
                        ValidateAudience = false
                    };
                });
            }

            //services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
            //    .AddMicrosoftIdentityWebApi(Configuration.GetSection("AzureAdB2C"));

        }
    }

    public class Audience
    {
        public string Secret { get; set; } = string.Empty;
        public string SecretFile { get; set; } = string.Empty;
        /// <summary>
        /// 发行人
        /// </summary>
        public string Issuer { get; set; } = string.Empty;
        /// <summary>
        /// 听众
        /// </summary>
        public string Audien { get; set; } = string.Empty;
    }
}
